package task1;

import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import org.apache.log4j.Logger;

public class TextSerializer implements Serializer {
	
	private static final Logger logger = Logger.getLogger(Serializer.class);
	
	private ITemplateFactory factory;
	private String fileName;
	private BufferedWriter outputBW;
	
	public TextSerializer(ITemplateFactory factory, String fileName) {
		logger.info("TextSerializer(ITemplateFactory, String) constructor");
		this.factory = factory;
		this.fileName = fileName;
	}
	
	/*
	 * (non-Javadoc)
	 * @see task1.Serializer#serialize(task1.DataItem)
	 * 
	 * Метод записывает в файл fileName текстовое представление 
	 * переменной типа DataItem
	 */
	public void serialize(DataItem newDI) {
		
		try {
			logger.info("TextSerializer.serialize(DataItem) method");
			outputBW = new BufferedWriter(
					 	new FileWriter(fileName, true));

			outputBW.write(factory.getTemplate(newDI));
			outputBW.newLine();

			outputBW.close();
		} catch (FileNotFoundException e) {
			logger.error("TextSerializer.serialize() error : File does not exist or for some reason is inaccessible", e);
		} catch (IOException e) {
			logger.error("TextSerializer.serialize() error : I/O exception has occurred", e);
		}
		
	}
}